package com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.activity.GameChoiceCircleButtonSecondActivity;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.adapter.GameChoiceBannerAdapter;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.adapter.GameChoiceGridViewAdapter;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.adapter.GameChoiceListViewAdapter;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.app.App;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.bean.GameChoiceBannerViewPagerInfo;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.bean.GameChoiceCircleInfo;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.bean.GameChoiceGridViewInfo;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.bean.GameChoiceMainInfo;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.bean.GameChoiceMainInfoParent;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.bean.GameChoiceRefreshHeader;
import com.example.administrator.daydayappmarket.game.fragment.fragments.choiceness.bean.MyGridViewGameChoice;
import com.example.administrator.daydayappmarket.software.utils.CircleIndicator;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * A simple {@link Fragment} subclass.
 */
public class GameChoicenessFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2<ListView>{

    private List<GameChoiceMainInfoParent> infoList;

    private List<GameChoiceBannerViewPagerInfo> bannerList;

    private List<GameChoiceCircleInfo> circleList;

    private List<GameChoiceGridViewInfo> gridViewList;

    private CircleIndicator indicator;

    private GameChoiceListViewAdapter choiceListAdapter;

    private GameChoiceBannerAdapter bannerAdapter;

    private LinearLayout linearLayout1;
    private LinearLayout linearLayout2;
    private LinearLayout linearLayout3;
    private LinearLayout linearLayout4;


    private int page=1;



    private View gridViewLayout;
    private MyGridViewGameChoice gridView;
    private GameChoiceGridViewAdapter gridViewAdapter;


    @InjectView(R.id.fragment_game_choiceness_pullToRefreshListView)
    PullToRefreshListView listView;

    private RequestQueue requestQueue;
    private ViewPager bannerViewpager;
    private View bannerView;

    private JSONArray jsonArray;

    public GameChoicenessFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initData();
        initVolley();


    }

    private void initVolley() {

        page=1;
        //1.获取请求
        requestQueue = App.getApp().getRequestQueue();

        //2.创建强求
        StringRequest stringRequest=new StringRequest(Request.Method.GET, Contacts.URL_GAME_CHOICENESS+page+Contacts.URL_GAME_CHOICENESS_END, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

//                Log.e("TAG", "onResponse: " + response );

                if (response != null) {
                    try {

                        //游戏精品下方的listView
                        jsonArray = new JSONArray(response);
                        JSONObject jsonObject1 = jsonArray.getJSONObject(3);

                        JSONArray data = jsonObject1.getJSONArray("data");

                        for (int i = 0; i < data.length(); i++) {

                            JSONObject jsonObject2 = data.getJSONObject(i);
                            GameChoiceMainInfo gameChoiceMainInfo = new GameChoiceMainInfo();
                            gameChoiceMainInfo.parseJson(jsonObject2);

                            infoList.add(gameChoiceMainInfo);
                        }

                        choiceListAdapter.notifyDataSetChanged();


                        //游戏精品上方的Banner广告
                        addHeadView(jsonArray,bannerList,circleList);
                        bannerViewpager.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View view, MotionEvent motionEvent) {

                                switch (motionEvent.getAction()){

                                    case MotionEvent.ACTION_DOWN:
                                        mHandler.removeCallbacks(mRunnable);

                                        break;
                                    case MotionEvent.ACTION_MOVE:
                                        break;

                                    case MotionEvent.ACTION_UP:
                                        mHandler.postDelayed(mRunnable,2000);
                                        break;
                                }

                                return false;
                            }
                        });

                        //游戏精品下方的GridView
                        addHeadGrid(jsonArray,gridViewList);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }



            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        })
        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> header=new HashMap<>();

                header.put("X-Client-Info","{\"channel\":\"tengxun\",\"device\":\"ZTE STAR\"," +
                        "\"version\":\"4.2.0\",\"imei\":\"864895023395203\",\"install_time\":" +
                        "\"1482716313042\",\"memory_size\":31576,\"metrics\":\"1080*1920\",\"" +
                        "os_version\":\"4.2.2\",\"project\":\"AppCenter\",\"uuid\":\"567b8d1b-" +
                        "dc0d-46a4-a4f5-62ac6a42a30c\",\"hasSIM\":true,\"version_code\":40007}");

                return header;

            }
        };

        //3.请求设置标签
        stringRequest.setTag("request");

        //4.添加到请求队列
        requestQueue.add(stringRequest);
    }

    private void addHeadGrid(JSONArray jsonArray,List<GameChoiceGridViewInfo> gridViewList) throws JSONException {

        gridViewList.clear();
        if(jsonArray!=null){

            JSONObject jsonObject3 = jsonArray.getJSONObject(2);
            JSONObject data3 = jsonObject3.getJSONObject("data");


            JSONArray apps = data3.getJSONArray("apps");
            for (int i = 0; i < apps.length(); i++) {

                JSONObject jsonObject4 = apps.getJSONObject(i);
                GameChoiceGridViewInfo gridViewInfo=new GameChoiceGridViewInfo();
                gridViewInfo.parseJson(jsonObject4);
                gridViewList.add(gridViewInfo);
            }


            gridViewAdapter=new GameChoiceGridViewAdapter(gridViewList,getContext());
            gridView.setAdapter(gridViewAdapter);
        }

    }

    private void addHeadView(JSONArray jsonArray,List<GameChoiceBannerViewPagerInfo> bannerList
    ,List<GameChoiceCircleInfo> circleList) throws JSONException {
        //游戏精品上方的Banner广告

        bannerList.clear();
        circleList.clear();
        if(jsonArray!=null){

            JSONObject jsonObject2 = jsonArray.getJSONObject(0);
            JSONArray data1 = jsonObject2.getJSONArray("data");
            for (int i = 0; i < data1.length(); i++) {

                JSONObject jsonObject = data1.getJSONObject(i);
                GameChoiceBannerViewPagerInfo bannerViewPagerInfo=
                        new GameChoiceBannerViewPagerInfo();

                bannerViewPagerInfo.parseJson(jsonObject);

                bannerList.add(bannerViewPagerInfo);
            }

            bannerAdapter=new GameChoiceBannerAdapter(bannerList,getContext());



            bannerViewpager.setAdapter(bannerAdapter);

//                        bannerViewpager.setCurrentItem(Integer.MAX_VALUE/2-((Integer.MAX_VALUE/2)%bannerList.size()),false);

            //圆形指示器
            indicator.setIndicatorMode(CircleIndicator.Mode.OUTSIDE);//设置圆形指示器模式
            indicator.setIndicatorRadius(10);//指示器圆的大小
            indicator.setIndicatorMargin(10);//设置圆之间的间隔

            indicator.setViewPager(bannerViewpager,bannerList.size());//圆形指示器和ViewPager相结合


            //游戏精品头部下方圆形按钮
            JSONObject jsonObject = jsonArray.getJSONObject(1);

            JSONArray data2 = jsonObject.getJSONArray("data");
            for (int i = 0; i < data2.length(); i++) {

                JSONObject jsonObject3 = data2.getJSONObject(i);
                GameChoiceCircleInfo choiceCircleInfo=new GameChoiceCircleInfo();
                choiceCircleInfo.parseJson(jsonObject3);

                circleList.add(choiceCircleInfo);
            }

            ViewGroup linearRoot = (ViewGroup) ((ViewGroup) bannerView).getChildAt(1);

            for (int i = 0; i < linearRoot.getChildCount(); i++) {
                ImageView imageView = (ImageView) ((ViewGroup) linearRoot.getChildAt(i)).getChildAt(0);
                TextView textView = (TextView) ((ViewGroup) linearRoot.getChildAt(i)).getChildAt(1);

                GameChoiceCircleInfo choiceCircleInfo = circleList.get(i);
                textView.setText(choiceCircleInfo.getTitle());
                Picasso.with(getContext()).load(Contacts.IMAGE_PREFIX+choiceCircleInfo.getImage()).into(imageView);

            }
        }


    }

    private void initData() {

        infoList=new ArrayList<>();

        bannerList=new ArrayList<>();

        circleList=new ArrayList<>();

        gridViewList=new ArrayList<>();

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_game_choiceness, container, false);
        ButterKnife.inject(this, view);

        RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.fragment_game_RelativeLayout_empty);
        ImageView imageView = (ImageView) view.findViewById(R.id.fragment_game_empty_image);
        Glide.with(getContext()).load(R.drawable.cat_loading_transparent).into(imageView);
        listView.setEmptyView(layout);

        gridViewLayout= LayoutInflater.from(getContext()).inflate(R.layout.item_game_choice_gridview,null);

        gridView= (MyGridViewGameChoice) gridViewLayout.findViewById(R.id.item_fragment_game_choice_gridview);

        bannerView = LayoutInflater.from(getContext()).inflate(R.layout.item_fragment_game_choice_header_banner, null);

        linearLayout1= (LinearLayout) bannerView.findViewById(R.id.item_fragment_game_choice_header_banner_bottom_layout_one);
        linearLayout2= (LinearLayout) bannerView.findViewById(R.id.item_fragment_game_choice_header_banner_bottom_layout_two);
        linearLayout3= (LinearLayout) bannerView.findViewById(R.id.item_fragment_game_choice_header_banner_bottom_layout_three);
        linearLayout4= (LinearLayout) bannerView.findViewById(R.id.item_fragment_game_choice_header_banner_bottom_layout_four);


        bannerViewpager = (ViewPager) bannerView.findViewById(R.id.item_fragment_game_choice_header_banner_viewPager);

        indicator = (CircleIndicator) bannerView.findViewById(R.id.item_fragment_game_choice_header_banner_indicator);

        choiceListAdapter=new GameChoiceListViewAdapter(infoList,getContext());

        listView.setAdapter(choiceListAdapter);

        listView.getRefreshableView().addHeaderView(bannerView);
        listView.getRefreshableView().addHeaderView(gridViewLayout);

        if(bannerList!=null&&circleList!=null){

            try {
                addHeadView(jsonArray,bannerList,circleList);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        if(gridViewList!=null){

            try {
                addHeadGrid(jsonArray,gridViewList);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }


        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(this);

        linearLayout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(getContext(), GameChoiceCircleButtonSecondActivity.class);

                intent.putExtra("id",circleList.get(0).getId());

                getActivity().startActivity(intent);
            }
        });

        linearLayout2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(getContext(), GameChoiceCircleButtonSecondActivity.class);

                intent.putExtra("id",circleList.get(1).getId());

                getActivity().startActivity(intent);
            }
        });

        linearLayout3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(getContext(), GameChoiceCircleButtonSecondActivity.class);

                intent.putExtra("id",circleList.get(2).getId());

                getActivity().startActivity(intent);
            }
        });

        linearLayout4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent=new Intent(getContext(), GameChoiceCircleButtonSecondActivity.class);

                intent.putExtra("id",circleList.get(3).getId());

                getActivity().startActivity(intent);
            }
        });


        return view;
    }

    //Viewpager 自动轮播

    Handler mHandler=new Handler();

    Runnable mRunnable=new Runnable() {
        @Override
        public void run() {

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    bannerViewpager.setCurrentItem(bannerViewpager.getCurrentItem()+1);

                }
            });
            //延时调用
            mHandler.postDelayed(mRunnable,3000);
        }
    };

   @Override
    public void onResume() {
        super.onResume();
         mHandler.postDelayed(mRunnable,3000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(mRunnable);

    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);

        requestQueue.cancelAll("request");
        requestQueue.cancelAll("request2");

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        infoList.clear();

        bannerList.clear();

        circleList.clear();

        gridViewList.clear();

        initVolley();
        refreshView.onRefreshComplete();

    }


    @Override
    public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {

        page++;

        //1.获取请求
        requestQueue = App.getApp().getRequestQueue();

        //2.创建强求
        StringRequest stringRequest=new StringRequest(Request.Method.GET, Contacts.URL_GAME_CHOICENESS+page+Contacts.URL_GAME_CHOICENESS_END, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

//                Log.e("TAG", "onResponse: " + response );

                if (response != null) {

                    try {
                        JSONArray jsonArray=new JSONArray(response);

                        JSONObject jsonObject2 = jsonArray.getJSONObject(0);
                        GameChoiceRefreshHeader gameChoiceRefreshHeader=new GameChoiceRefreshHeader();
                        gameChoiceRefreshHeader.parseJson(jsonObject2);
                        infoList.add(gameChoiceRefreshHeader);



                        JSONObject jsonObject = jsonArray.getJSONObject(1);
                        JSONArray data = jsonObject.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {

                            JSONObject jsonObject1 = data.getJSONObject(i);
                            GameChoiceMainInfo gameChoiceMainInfo=new GameChoiceMainInfo();
                            gameChoiceMainInfo.parseJson(jsonObject1);

                            infoList.add(gameChoiceMainInfo);
                        }

                        choiceListAdapter.notifyDataSetChanged();
                        refreshView.onRefreshComplete();



                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }



            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        })
        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> header=new HashMap<>();

                header.put("X-Client-Info","{\"channel\":\"tengxun\",\"device\":\"ZTE STAR\"," +
                        "\"version\":\"4.2.0\",\"imei\":\"864895023395203\",\"install_time\":" +
                        "\"1482716313042\",\"memory_size\":31576,\"metrics\":\"1080*1920\",\"" +
                        "os_version\":\"4.2.2\",\"project\":\"AppCenter\",\"uuid\":\"567b8d1b-" +
                        "dc0d-46a4-a4f5-62ac6a42a30c\",\"hasSIM\":true,\"version_code\":40007}");

                return header;

            }

        };

        //3.请求设置标签
        stringRequest.setTag("request2");

        //4.添加到请求队列
        requestQueue.add(stringRequest);


    }
}
